import { videoCache } from './videoCache';

type MediaType = 'video' | 'image';
type MediaItem = {
  url: string;
  type: MediaType;
};

class MediaPreloadManager {
  private isPreloading: boolean = false;
  private preloadQueue: MediaItem[] = [];
  private maxConcurrent: number = 2;

  // 添加预加载队列
  addMedia(items: (string | MediaItem)[], type: MediaType = 'video') {
    const mediaItems = items.map((item) => (typeof item === 'string' ? { url: item, type } : item));

    mediaItems.forEach((item) => {
      const exists = this.preloadQueue.some((queueItem) => queueItem.url === item.url && queueItem.type === item.type);
      if (!exists) {
        this.preloadQueue.push(item);
      }
    });
  }

  // 添加视频
  addVideos(urls: string[]) {
    this.addMedia(urls, 'video');
  }

  // 添加图片
  addImages(urls: string[]) {
    this.addMedia(urls, 'image');
  }

  // 开始预加载
  async startPreload(onProgress?: (progress: number) => void) {
    if (this.isPreloading) {
      console.log('Preload already in progress');
      return;
    }

    this.isPreloading = true;
    let completed = 0;

    try {
      // 分批处理，控制并发数
      for (let i = 0; i < this.preloadQueue.length; i += this.maxConcurrent) {
        const batch = this.preloadQueue.slice(i, i + this.maxConcurrent);

        await Promise.all(
          batch.map(async (item) => {
            try {
              if (item.type === 'video') {
                await videoCache.getVideoUri(item.url);
              } else {
                // TODO 暂时不缓存图片
                // await imageCache.getImageUri(item.url);
              }
              completed++;

              if (onProgress) {
                const progress = (completed / this.preloadQueue.length) * 100;
                onProgress(progress);
              }
            } catch (error) {
              console.error(`Failed to preload ${item.type}: ${item.url}`, error);
            }
          }),
        );
      }
    } catch (error) {
      console.error('Preload failed:', error);
    } finally {
      this.isPreloading = false;
      this.preloadQueue = [];
    }
  }

  // 停止预加载
  stopPreload() {
    this.preloadQueue = [];
    this.isPreloading = false;
  }

  // 检查是否正在预加载
  isPreloadInProgress(): boolean {
    return this.isPreloading;
  }

  // 获取队列状态
  getQueueStatus() {
    const videos = this.preloadQueue.filter((item) => item.type === 'video').length;
    const images = this.preloadQueue.filter((item) => item.type === 'image').length;
    return {
      total: this.preloadQueue.length,
      videos,
      images,
      isPreloading: this.isPreloading,
    };
  }

  // 设置最大并发数
  setMaxConcurrent(num: number) {
    this.maxConcurrent = Math.max(1, Math.min(num, 5)); // 限制在1-5之间
  }

  // 清理所有缓存
  async clearAllCache() {
    try {
      await Promise.all([
        videoCache.clearCache(),
        // imageCache.clearCache()
      ]);
    } catch (error) {
      console.error('Failed to clear cache:', error);
      throw error;
    }
  }
}

export const mediaPreload = new MediaPreloadManager();
